package mks.plugin.popup.actions;

import java.io.File;
import java.io.FilenameFilter;
import mks.plugin.MKSCommand;
import org.eclipse.core.internal.resources.Project;
import org.eclipse.core.resources.IFile;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IActionDelegate;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

public abstract class MKSAction implements IObjectActionDelegate {

    protected Object[]   itemSelected;
    protected Shell      shell;
    protected MKSCommand mksCommand;

    public abstract void runCommand(String filename, File directory);

    /**
     * @see IObjectActionDelegate#setActivePart(IAction, IWorkbenchPart)
     */
    public void setActivePart(IAction action, IWorkbenchPart targetPart) {
        shell = targetPart.getSite().getShell();
    }

    /**
     * @see IActionDelegate#selectionChanged(IAction, ISelection)
     */
    public void selectionChanged(IAction action, ISelection selection) {
        IStructuredSelection selected = (IStructuredSelection) selection;

        itemSelected = selected.toArray();
    }

    /**
     * @see IActionDelegate#run(IAction)
     */
    public void run(IAction action) {
        if (itemSelected == null) {
            MessageDialog.openError(shell, "MKS Plug-in", "No item selected");
        }
        else {
            for (Object item : itemSelected) {
                mksCommand = new MKSCommand(shell);
                if (item instanceof IFile) {
                    IFile file = (IFile) item;
                    runCommand(file.getName(), file.getRawLocation().toFile().getParentFile());
                }
                else if (item instanceof Project) {

                    File dir = (((Project) item).getLocation().toFile());

                    File[] pjFile = dir.listFiles(new FilenameFilter() {
                        public boolean accept(File dir, String name) {
                            return name.contains(".pj");
                        }

                    });

                    StringBuffer sb = new StringBuffer();
                    sb.append("--sandbox=");
                    sb.append(dir.getAbsolutePath());
                    sb.append(File.separator);
                    sb.append(pjFile[0].getName());

                    runCommand(sb.toString(), dir);
                }
            }
        }
    }

}
